<?php
namespace Tongcheng\Controller;
use Think\Controller;
class CommonController extends Controller {
    public function _initialize(){
        //deleteprinter('4004556169','090683ec0427469bac1df18d122109b6');
        //达达添加订单
    //$this->addorder();
        //易联云测试token
        //$this->getdyj_token();
        //易联云测试打印
        //$this->printOrder();
        //$this->addprinter();
    	if(!session('?uid')){
    		$this->redirect("Home/Public/login");
    	}
        if($_GET['wid']){
            $map['uid'] = session('uid');
            $map['wid'] = $_GET['wid'];

            if($wechat = M("Wechat")->where($map)->find()){
                if($wechat['end_time'] < date("Y-m-d")){
                    $this->error("小程序已到期，请联系管理员续期");
                }
                if($wechat['status'] == 0){
                    $this->error("该小程序已被限制使用");
                }
                session('wid', $_GET['wid']);
                session('wechat.nickname', $wechat['nick_name']);
                session('wechat.headimg', $wechat['head_img']);
            }else{
                $this->error('请选择要管理的小程序',U('Home/Index/index'));
            }
        }
        if(!session('?wid')){
            $this->error('请选择要管理的小程序',U('Home/Index/index'));
        }
    }
    //打印机测试
    public function getdyj_token()
    {
        vendor('openapi-sdk.lib.YLYTokenClient');
        //require_once (__DIR__.'/lib/YLYTokenClient.php');
        $token = new \YLYTokenClient();

        //获取token;
        $grantType = 'client_credentials';  //自有模式(client_credentials) || 开放模式(authorization_code)
        $scope = 'all';                     //权限
        $timesTamp = time();                //当前服务器时间戳(10位)
        //$code = '';                       //开放模式(商户code)
        echo  $token->GetToken($grantType,$scope,$timesTamp);

        //刷新token;
        $grantType = 'refresh_token';       //自有模式或开放模式一致
        $scope = 'all';                     //权限
        $timesTamp = time();                //当前服务器时间戳(10位)
        $RefreshToken = '';                 //刷新token的密钥
        echo $token->RefreshToken($grantType,$scope,$timesTamp,$RefreshToken);
    }


    /*
     * 易联云测试添加授权打印机
     * @param $machineCode
     * @param $msign or $qrKey
     * @param $accessToken
     * @param $timesTamp
     * */
    public function addprinter()
    {
        vendor('openapi-sdk.lib.YLYOpenApiClient');
        $api = new \YLYOpenApiClient();
        $machineCode = "4004556169";
        $msign = "ikdeh3e3f8kq";
        $accessToken = "07d681912454445f8f60ff0262154755";
        $timesTamp = time();
        echo $api->addPrint($machineCode, $msign, $accessToken, $timesTamp);
    }
    //打印机打印
    public function printOrder()
    {
        vendor('openapi-sdk.lib.YLYOpenApiClient');
        $api = new \YLYOpenApiClient();

        $content = '';                          //打印内容
        $content .= '<FS><center>8号桌</center></FS>';
        $content .= str_repeat('-',32);
        $content .= '<FS><table>';
        $content .= '<tr><td>商品</td><td>数量</td><td>价格</td></tr>';
        $content .= '<tr><td>土豆回锅肉</td><td>x1</td><td>￥20</td></tr>';
        $content .= '<tr><td>干煸四季豆</td><td>x1</td><td>￥12</td></tr>';
        $content .= '<tr><td>苦瓜炒蛋</td><td>x1</td><td>￥15</td></tr>';
        $content .= '</table></FS>';
        $content .= str_repeat('-',32)."\n";
        $content .= '<FS>金额: 47元</FS>';

        $machineCode = '4004556169';                      //授权的终端号
        $accessToken = '07d681912454445f8f60ff0262154755';                      //api访问令牌
        $originId = $this->build_order_no();                         //商户自定义id
        $timesTamp = time();                    //当前服务器时间戳(10位)
        $api->printIndex($machineCode,$accessToken,$content,$originId,$timesTamp);

    }


    //达达获取程序code
    public function getCityCode()
    {
        vendor('dada.DadaOpenapi');
        //*********************配置项*************************
        $config = array();
        $config['app_key'] = 'dada6c851e9842f83ac';
        $config['app_secret'] = '84c83ce31b0fd8c6d5c5c5fa05d51dc1';
        $config['source_id'] = '73753';
        $config['url'] = 'http://newopen.qa.imdada.cn/api/cityCode/list';

        $obj = new \DadaOpenapi($config);
        //***********************查询接口************************
        $data=array();
        $reqStatus = $obj->makeRequest($data);
        $re = $obj->getResult();
        //$re = array_search('临沂',$re);
        var_dump($re);exit;
    }

    /**
     * 新达达开放平台发单接口DEMO
     * 详情：发单
     * 版本：1.0
     * 日期：2016-09-10
     * 说明：
     * 以下代码只是为了方便对接商户测试而提供的样例代码，对接商户可以根据自己的需求，按照技术文档编写，代码仅供参考。
     */
    public function addorder(){
        $citycode = $this->getCityCode();
        vendor('dada.DadaOpenapi');
        //*********************配置项*************************
        $config = array();
        $config['app_key'] = 'dada6c851e9842f83ac';
        $config['app_secret'] = '84c83ce31b0fd8c6d5c5c5fa05d51dc1';
        $config['source_id'] = '73753';
        $config['url'] = 'http://newopen.qa.imdada.cn/api/order/addOrder';

        $obj = new \DadaOpenapi($config);

        //***********************发单接口************************
        //发单请求数据,只是样例数据，根据自己的需求进行更改。
        $data = array(
            'shop_no'=> '11047059',
            'origin_id'=> $this->build_order_no(), //第三方订单ID
            'city_code'=> $citycode,
            'info'=> '测试订单',
            'cargo_price'=> 10,
            'is_prepay'=> 0,
            'expected_fetch_time'=> 1471536000,
            'receiver_name'=> '测试',
            'receiver_address'=> '上海市崇明岛',
            'receiver_phone'=> '18588888888',
            'receiver_tel'=> '18599999999',
            'receiver_lat'=> 31.63,
            'receiver_lng'=> 121.41,
            'callback'=>'http://newopen.imdada.cn/inner/api/order/status/notify'
        );

        //请求接口
        $reqStatus = $obj->makeRequest($data);
        var_dump($reqStatus);
        if (!$reqStatus) {
            //接口请求正常，判断接口返回的结果，自定义业务操作
            if ($obj->getCode() == 0) {
                //返回成功 ....
            }else{
                //返回失败
            }
            echo sprintf('code:%s，msg:%s', $obj->getCode(), $obj->getMsg());
        }else{
            //请求异常或者失败
            echo 'except';
        }




    }
    protected function build_order_no(){
        return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
    protected function ihttp_post($url, $post_data){
    	$ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $out = curl_exec($ch);
        curl_close($ch);
        return $out;
    }

    protected function ihttp_get($url, $is_https = true){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if($is_https){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        $out = curl_exec($ch);
        curl_close($ch);
        return $out;
    }

    /*
     * 365小票打印
     *
     * */
    protected function sendSelfFormatOrderInfo($device_no,$key,$times,$orderInfo){ // $times打印次数
        $selfMessage = array(
            'deviceNo'=>$device_no,
            'printContent'=>$orderInfo,
            'key'=>$key,
            'times'=>$times
        );
        $url = "http://open.printcenter.cn:8080/addOrder";
        $options = array(
            'http' => array(
                'header' => "Content-type: application/x-www-form-urlencoded ",
                'method'  => 'POST',
                'content' => http_build_query($selfMessage),
            ),
        );
        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);

        return $result;
    }
}